const ejs = require('ejs')
const fs = require('node:fs')
const marked = require('marked')
const path = require('node:path')
let browser
const broeswrSync = require('browser-sync')
const server = () => {
    browser = broeswrSync.create()
    browser.init({
        server: {
            baseDir: './',
            index: 'index.html'
        }
    })
}
const init = (callback) => {
    // 读取 md 内容
    const md = fs.readFileSync('./index.md', 'utf-8')
    ejs.renderFile('./template.ejs', {
        title: path.parse(path.resolve('./template.ejs')).name,
        content: marked.parse(md)
    }, (err, data) => {
        if (err) return console.log(err)
        fs.writeFileSync('./index.html', data)
        callback()
    })
}
fs.watchFile('./index.md', (curr, prev) => {
    if (curr.mtime !== prev.mtime) {
        init(() => {
            browser.reload()
        })
    }
})
init(() => {
    server()
})